package com.hxzy.tms.interceptor;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.hxzy.tms.HibernateSessionHolder;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class Hibernate‌Interceptor extends AbstractInterceptor {
	private static final long serialVersionUID = -8598742796549307651L;
	private SessionFactory sessionFsctory;
	@Override
	public void init() {
		Configuration conftiguration = new Configuration().configure();
		this.sessionFsctory = conftiguration.buildSessionFactory();
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Session session = this.sessionFsctory.openSession();
		String actionResult = null;
		try {
			HibernateSessionHolder.set(session);
			actionResult = invocation.invoke();
		} finally {
			if (HibernateSessionHolder.get().isOpen()) {
				HibernateSessionHolder.get().close();
			}
		}
		return actionResult;

	}
  @Override
	public void destroy() {
	   if (this.sessionFsctory!=null){
		   this.sessionFsctory.close();
	   }
	}
}
